package com.mobile.liuyi_s.orderlunch.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.mobile.liuyi_s.orderlunch.MainActivity;
import com.mobile.liuyi_s.orderlunch.MyApplication;
import com.mobile.liuyi_s.orderlunch.R;
import com.mobile.liuyi_s.orderlunch.Utils.Utils;
import com.mobile.liuyi_s.orderlunch.entity.MyUser;

import cn.bmob.v3.BmobUser;
import rx.Subscriber;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";
//    private static final int QUERY_USER_ASYNC_FLAG = 111;
//    private static final int QUERY_ORDR_INFO = 123;
//    private static final int GET_LOGIN_PERMISSION = 131;
    private InputMethodManager mInputMethodManager;
    private MyApplication mApplication;

    private EditText mEditTextUserName;
    private EditText mEditTextPwd;
    private Button mButtonLogin;
    private Button mButtonSignUp;
    private ProgressBar mProgressBar;
    private Toolbar mToolbar;

    private String inputUserName;
    private String inputUserPwd;
//    private String corrUserName;
//    private String corrUserPwd;
//    private String corrUserGroup;
//    private boolean isOrdered;

//    private boolean isLoginSuccess = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        mInputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
//        mApplication = ((MyApplication) getApplication());
    }

    private void initView() {
        initToolbar();
        mEditTextUserName = ((EditText) findViewById(R.id.login_user_name));
        mEditTextPwd = ((EditText) findViewById(R.id.login_user_pwd));
        mButtonLogin = ((Button) findViewById(R.id.login_confirm_button));
        mButtonSignUp = ((Button) findViewById(R.id.login_sign_up_button));
        mProgressBar = ((ProgressBar) findViewById(R.id.login_progress_bar));
        mButtonSignUp.setOnClickListener(this);
        mButtonLogin.setOnClickListener(this);
    }

    private void initToolbar() {
        mToolbar = ((Toolbar) findViewById(R.id.toolbar_login));
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.login_confirm_button:
//                setClickable(false);
                Utils.hideKeyBoard(this, mInputMethodManager);
                inputUserName = mEditTextUserName.getText().toString().trim();
                inputUserPwd = mEditTextPwd.getText().toString().trim();
                if (inputUserName.length() >= 2 && inputUserPwd.length() > 0) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    //TODO: check pwd from DB and set progress bar
//                    queryUserInfo();
//                    queryOrderInfo();
                    userLogin(inputUserName, inputUserPwd);
//                    Log.d(TAG, "onClick: "+corrUserGroup);
//                    queryOrderInfo();
//                    mApplication.setOrdered(isOrdered);
                } else {
                    Toast.makeText(this, "输入用户名或密码长度不符", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.login_sign_up_button:
                mProgressBar.setVisibility(View.INVISIBLE);
                mEditTextPwd.setText("");
                mEditTextUserName.setText("");
                Intent intent = new Intent(this, SignUpActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
    private void userLogin(String username, String password) {
        BmobUser bmobUser = new BmobUser();
        bmobUser.setUsername(username);
        bmobUser.setPassword(password);
        bmobUser.loginObservable(MyUser.class).subscribe(new Subscriber<MyUser>() {
            @Override
            public void onCompleted() {
                mProgressBar.setVisibility(View.INVISIBLE);
//                setClickable(true);
                Toast.makeText(mApplication, "登录失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable throwable) {
                mProgressBar.setVisibility(View.INVISIBLE);
                String errorInfo = throwable.toString();
                Log.d(TAG, "onError: " + errorInfo);
                if (errorInfo.contains("101")) {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                } else if (errorInfo.contains("9016") || errorInfo.contains("SocketTimeout")) {
                    Toast.makeText(LoginActivity.this, "目前网络不可用，稍后再试试！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, "未知错误", Toast.LENGTH_SHORT).show();
                }
//                setClickable(true);
            }

            @Override
            public void onNext(MyUser myUser) {
                mProgressBar.setVisibility(View.INVISIBLE);
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
//        BmobUser currUser = BmobUser.getCurrentUser();
//        if (currUser != null) {
//
//            corrUserGroup = ((String) MyUser.getObjectByKey("userGroup"));
//            if (corrUserGroup != null) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                startActivity(intent);
//            } else {
//                Log.d(TAG, "userLogin: 用户组获取失败");
//            }
//
//            Log.d(TAG, "userLogin: " + corrUserGroup);
//        } else {
//            Toast.makeText(mApplication, "未缓存用户", Toast.LENGTH_SHORT).show();
//        }
    }
    private void setClickable(boolean isClickable) {
        mButtonLogin.setClickable(isClickable);
        mButtonSignUp.setClickable(isClickable);
        mEditTextUserName.setFocusable(isClickable);
        mEditTextPwd.setFocusable(isClickable);
    }

//    private void queryUserInfo() {
//        BmobQuery<MyUser> query = new BmobQuery<>();
//        query.addWhereEqualTo("userName", inputUserName);
////        Log.d(TAG, "userName:::" + inputUserName);
//        query.findObjects(new FindListener<MyUser>() {
//            @Override
//            public void done(List<MyUser> object, BmobException e) {
//                if (e == null) {
//                    if (object.size() == 0) {
//                        Toast.makeText(LoginActivity.this, "用户名错误", Toast.LENGTH_SHORT).show();
//                    } else {
//                        Message message = mHandler.obtainMessage();
//                        message.what = QUERY_USER_ASYNC_FLAG;
//                        message.obj = object;
//                        mHandler.sendMessage(message);
//                    }
//                } else {
//                    Toast.makeText(LoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
//                }
//            }
//
//        });
//    }

//    private void queryOrderInfo() {
//        Utils utils = new Utils();
//        BmobQuery<Order> queryUser = new BmobQuery<>();
//        queryUser.addWhereEqualTo("userName", corrUserName);
//        BmobQuery<Order> queryYear = new BmobQuery<>();
//        queryYear.addWhereEqualTo("orderYear", utils.getLocacYear());
//        BmobQuery<Order> queryMonth = new BmobQuery<>();
//        queryMonth.addWhereEqualTo("orderMonth", utils.getLocacMonth());
//        BmobQuery<Order> queryDay = new BmobQuery<>();
//        queryDay.addWhereEqualTo("orderDay", utils.getLocacDay());
//        ArrayList<BmobQuery<Order>> queries = new ArrayList<>();
//        queries.add(queryUser);
//        queries.add(queryYear);
//        queries.add(queryMonth);
//        queries.add(queryDay);
//        BmobQuery<Order> mainQuery = new BmobQuery<>();
//        mainQuery.and(queries);
//        mainQuery.findObjects(new FindListener<Order>() {
//            @Override
//            public void done(List<Order> list, BmobException e) {
//                if (e == null) {
//                    Message message = mHandler.obtainMessage();
//                    message.what = QUERY_ORDR_INFO;
//                    message.obj = list;
//                    mHandler.sendMessage(message);
//                } else {
//                    Log.d(TAG, "done: 复合查询用户订单信息失败");
//                }
//            }
//        });
//    }

//    private Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case QUERY_USER_ASYNC_FLAG:
//                    List<MyUser> userList = (List<MyUser>) msg.obj;
//                    corrUserName = userList.get(0).getUserName();
//                    corrUserPwd = userList.get(0).getUserPwd();
//                    corrUserGroup = userList.get(0).getUserGroup();
////                    corrUserObjectId = userList.get(0).getObjectId();
//
//                    if (corrUserName.equals(inputUserName) && corrUserPwd.equals(inputUserPwd)) {
//                        /*************************************************
//                         * 全局变量设置
//                         * **********************************************/
//                        MyUser user = new MyUser();
//                        user.setUserName(corrUserName);
//                        user.setUserGroup(corrUserGroup);
//                        user.setUserPwd(corrUserPwd);
////                        user.setObjectId(corrUserObjectId);
//                        mApplication.userLogin(user);
//
//                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                        startActivity(intent);
//                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
//                        LoginActivity.this.finish();
//                    } else {
//                        Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
//                    }
//                    break;

//                case QUERY_ORDR_INFO:
//                    List<Order> orderList = (List<Order>) msg.obj;
//                    if (orderList.size() == 0) {
//                        isOrdered = false;
//                    } else {
//                        isOrdered = true;
//                    }
//                    mApplication.setOrdered(isOrdered);
//                    Log.d(TAG, "handleMessage: isOrdered" + isOrdered);
//                    break;
//            }
//        }
//    };

}
